package cn.tedu._04weibo.controller;

import cn.tedu._04weibo.base.response.JsonResult;
import cn.tedu._04weibo.base.response.StatusCode;
import cn.tedu._04weibo.mapper.UserMapper;
import cn.tedu._04weibo.pojo.dto.UserLoginParam;
import cn.tedu._04weibo.pojo.dto.UserRegParam;
import cn.tedu._04weibo.pojo.entity.User;
import cn.tedu._04weibo.pojo.vo.UserVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpSession;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@Slf4j
@RestController
@RequestMapping("/v1/user")
@Tag(name = "01-用户管理模块")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @PostMapping("reg")
    @Operation(summary = "注册")
    @ApiOperationSupport(order = 10)
    public JsonResult reg(@RequestBody UserRegParam userRegParam){
        log.debug("开始处理【注册】的请求，参数：{}",userRegParam);
        User user = new User();
        BeanUtils.copyProperties(userRegParam,user);
        user.setCreateTime(new Date());
        log.debug("准备将用户数据插入到数据库中：{}",user);
        if(userMapper.selectUserByUsername(user.getUsername())!=0){
            return new JsonResult(StatusCode.USERNAME_EXIST);
        }

        if (userMapper.insertUser(user)>0){
            return JsonResult.ok();
        }else
            return new JsonResult(StatusCode.OPERATION_FAILED);
    }

    @PostMapping("login")
    @Operation(summary = "登录")
    @ApiOperationSupport(order = 20)
    public JsonResult login(@RequestBody UserLoginParam userloginParam, HttpSession  session){
        log.debug("开始处理【登录】的请求，参数：{}",userloginParam);
        UserVO userVO = userMapper.selectUserByUsernameAndPassword(userloginParam);
        if(userVO==null){
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }else
            session.setAttribute("user",userVO);
            return JsonResult.ok(userVO);
    }

    @GetMapping("currenUser")
    @Operation(summary = "获取当前登录用户")
    @ApiOperationSupport(order = 30)
    public JsonResult currenUser(HttpSession session){
        log.debug("开始处理【获取当前登录用户】的请求");
        UserVO userVO = (UserVO) session.getAttribute("user");
        if(userVO==null){
            return new JsonResult(StatusCode.NOT_LOGIN);
        }else
            return JsonResult.ok(userVO);
    }

    @GetMapping("logout")
    @Operation(summary = "退出登录")
    @ApiOperationSupport(order = 40)
    public JsonResult logout(HttpSession session){
        log.debug("开始处理【退出登录】的请求");
        session.removeAttribute("user");
        return JsonResult.ok();
    }

}
